package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IXunFeiService;
import com.ruoyi.system.util.xfyun.utils.RemoveQuotesAndBrackets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IAiRecordingMainService;

/**
 * 录音文件上传记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class AiRecordingMainServiceImpl implements IAiRecordingMainService
{
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private AiRecordingMainMapper aiRecordingMainMapper;
    @Autowired
    private AiDeepseekAnswerMapper aiDeepseekAnswerMapper;
    @Autowired
    private SystemFileMapper systemFileMapper;
    @Autowired
    private IXunFeiService iXunFeiService;
    @Autowired
    private AiRecordingChildMapper aiRecordingChildMapper;
    @Autowired
    private AiRecordingDuanMapper aiRecordingDuanMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private AiDeepseekAnswerTotalMapper aiDeepseekAnswerTotalMapper;

    @Autowired
    private AiDeepseekSpokesmanMapper aiDeepseekSpokesmanMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private DeepSeekClient deepSeekClient;

//    @Autowired
//    private AiDeepseekSpokesmanMapper aiDeepseekSpokesmanMapper;

//    private static final String FENXI = "## 定位\n" +
//            "你是加易加公司的中英双语销售对话分析师，专注客户沟通要素提取与商机预测\n" +
//            "\n" +
//            "## 核心能力\n" +
//            "1. **结构化解析**\n" +
//            "   - 检测预设关键词（介绍公司/介绍产品/介绍案例）\n" +
//            "   - 识别客户生命周期阶段（新客/老客/无法判断）\n" +
//            "   - 行业领域精准识别（制造业细分领域）\n" +
//            "   - 产品识别,检测交流的产品名称或产品类型,产品名称可以参考加易加产品,或其他相关酸、甜、饲料原料、定制开发的产品。提取产品时，必须严格确认语句中有明确说到的产品名称，否则只提取产品类型。定制开发的产品必须有明确说明客户提供配方加易加生产。\n" +
//            "2. **风险评估**\n" +
//            "   - 流失风险四级分类（高/中/低/未知）\n" +
//            "   - 动态生成风险判定依据\n" +
//            "   - 成交意愿三维评级（高/中/低）\n" +
//            "3. **需求洞察**\n" +
//            "   - 核心诉求提取,寻找合作伙伴或供应商的长期目的或主要考察点(单句概括)\n" +
//            "   - 业务痛点定位,需要合作伙伴或供应商立刻解决的问题(单句概括)\n" +
//            "   - 成交阻碍因素提取,客户无法接受的因素,或会造成客户流失的因素(提取1-5个关键要素短句)\n" +
//            "4. **客户画像**\n" +
//            "   - 检测预设三大类标签\n" +
//            "   - 客户类型三维分类（新客户/老客户/未知）\n" +
//            "5.**交流摘要**\n" +
//            "   - 将sales manager和costomer交流的内容进行总结概述，200字以内\n" +
//            "6.**有效交流**\n" +
//            "   - 有效交流二维分类（有效/无效）\n" +
//            "   - 判断该次交流是否为有效交流。有效交流是指：交流双方谈话内容需要包括以下任何内容加易加公司、客户公司、竞争对手、产品、市场、合作方式等与达成销售目的有关的交流\n" +
//            "\n" +
//            "## 知识体系\n" +
//            "### 关键词库\n" +
//            "- 介绍公司\n" +
//            "- 介绍产品\n" +
//            "- 邀请访厂\n" +
//            "- 送样品\n" +
//            "- 询问需求\n" +
//            "- 添加量\n" +
//            "- 添加成本\n" +
//            "- 介绍客户案例\n" +
//            "- 催促下单\n" +
//            "\n" +
//            "### 标签体系\n" +
//            "- 行业标签：#饲料加工 #化工原料 #生物制剂 #添加剂 #饲料原料 #代理商\n" +
//            "- 综合标签：#价格敏感 #技术导向 #决策链复杂 #强调实力 #实践效果 #期待合作 #期待合作 #质疑质量  #质疑实力 #需要账期\n" +
//            "- 风险标签：#竞品对比 #报价过高 #技术不足 #与竞争对手合作 #不好的经历 \n" +
//            "\n" +
//            "### 加易加公司产品\n" +
//            "化工产品：甲酸、丙酸、丁酸、柠檬酸等酸类产品及相关酸盐（如甲酸钙、丙酸氨等）\n" +
//            "酸化剂：由上述原料通过复配等方法制成的复合饲料添加剂、环境消杀剂等\n" +
//            "甜味剂：引诱动物增加饲料食用的饲料添加剂\n" +
//            "饲料原料：豆粕、蛋白等饲料原料\n" +
//            "定制产品：客户委托加易加生产的饲料添加剂\n" +
//            "产品类型：饲料品质、防霉保水、动物营养、牧场健康、谷物储运、原料单品、香甜产品、贴牌产品\n" +
//            "产品名称示例：U500\n" +
//            "\n" +
//            "### 其他说明\n" +
//            "- 新客户：不了解加易加公司需要向客户介绍，没有从加易加公司采购的经历\n" +
//            "- 介绍案例：有哪些客户使用加易加公司产品，或加易加公司与哪些客户合作\n" +
//            "- 介绍公司：介绍公司的资产、工厂、设备、市场占有率、排名、产品、生产能力、研发能力等\n" +
//            "- 产品注册:  加易加公司的产品向中国以外地区销售时，部分国家进口商需要在当地政府备案需要进口产品的资料，包括生产厂家、产品配方、产品名称等资料，通常称之为注册产品\n" +
//            "- 公司品牌：加易加公司拥有加易加(addeasy)、超甜易加(sweeteasy)、优尼特(unite)三个品牌\n" +
//            "\n" +
//            "## 处理规则\n" +
//            "### 输入规范\n" +
//            "- 对话格式：[sales manager]:...[customer]:...[unclear]:...\n" +
//            "- 语言混合：支持中英夹杂内容分析\n" +
//            "- 身份: sales manager是加易加公司的销售，customer是正在沟通的客户或其他人,unclear无法确定说话人身份，且unclear语句中存在既有客户也有销售的谈话内容" +
//            "\n" +
//            "## 输出规范\n" +
//            "用以下的形式输出,并且每一行用分号结尾\n" +
//            "```txt\n" +
//            "{\n" +
//            "  \"有效交流\": \"有效\";\n" +
//            "  \"关键词\": \"讲产品\", \"讲案例\";\n" +
//            "  \"新老客户\": \"老客户\";\n" +
//            "  \"流失风险\": \"低\";\n" +
//            "  \"流失风险说明\": \"客户持续探讨产品升级方案\";\n" +
//            "  \"成交意愿\": \"高\";\n" +
//            "  \"成交意愿说明\": \"主动要求提供报价明细\";\n" +
//            "  \"标签\": \"#价格敏感\", \"#化工原料\";\n" +
//            "  \"客户所在行业\": \"精细化工\";\n" +
//            "  \"核心诉求\": \"产品迭代后的质量稳定性\";\n" +
//            "  \"业务痛点\": \"寻找可定制配方的原料供应商\";\n" +
//            "  \"成交阻碍因素\": \"付款周期\", \"质量保证\", \"最小起订量\";\n" +
//            "  \"交流摘要\": \"客户重点咨询产品定制能力，已进入具体参数讨论阶段\";\n" +
//            "  \"产品\": \"Baograin,Fresilo,ADA,TMR,MoistMax,Antimold,Donal,ToxinClean,Fepro,Salstop,Salvator,Swemmy,Nulloxy,Zeroxy,Tasty,Optim,Vitacid,Megacid,Extramet,Mesto,Courea,Coda,Butyplus,Butysmart,VB,Gutpro,Gutclean,Cotan,Tanbo,Extragut,Essen,Phytomed,GML,Gutmax,Joymax,Germclean,Power,Spow,Calfacid,Aqual,Puracid,Fepro-FA,Freshco,Medos,超级酸,乐味酸,克霉灵,六乐酸,防霉剂,畅乐葆,易加酸,酸霸,大蒜素,鲜活U500,酸圈圈,维泽慕,乐多酸,惠酸,维肠乐,四甲酸一铵,易鲜宝,克霉先,意赛多纷,乳清酸,克霉消,硫醚沙星,美味酸\"\n" +
//            "}\n" +
//            "```\n" +
//            "\n" +
//            "### 质量控制\n" +
//            "1.关键词匹配：严格对照预设关键词库进行模式匹配,了解sales manager的行为有没有匹配关键词，不能自己使用关键词库以外的关键词\n" +
//            "2.双重校验机制：采用语义+关键词双重验证\n" +
//            "3.置信度：置信度低于0.7不采纳\n" +
//            "\n" +
//            "## 以下是用户输入内容";
//

    public String getFenxiDict() throws Exception {
        SysDictData promptWordsDict= sysDictDataMapper.selectDictDataByTypeOne("prompt_words");
        SysDictData labelDict= sysDictDataMapper.selectDictDataByTypeOne("label");
        SysDictData keywordDict= sysDictDataMapper.selectDictDataByTypeOne("keyword");
        String promptWords=   promptWordsDict.getRemark();
        String label=  labelDict.getRemark();
        String keyword=  keywordDict.getRemark();
       String result=  promptWords.replace("label", label).replace("keyword", keyword);
        return result;
    }




    @Override
    public AjaxResult deepseekParse(AiRecordingDuan aiRecordingDuan) throws Exception {
        Long mainId=aiRecordingDuan.getMainId();
        AiRecordingMain aiRecordingMain=new AiRecordingMain();
        aiRecordingMain.setId(mainId);
        aiRecordingMain.setStatus("5");
        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);

        getDeepSeekFor(aiRecordingDuan);
        return AjaxResult.success();
    }
    @Async // 标记为异步方法
    public  void getDeepSeekFor(  AiRecordingDuan aiRecordingDuan) throws Exception {
        Long duanId=aiRecordingDuan.getId();
       Long mainId=aiRecordingDuan.getMainId();
        String batchId=aiRecordingDuan.getBatchId();
        Long customerId=aiRecordingDuan.getCustomerId();
        Date time=aiRecordingDuan.getTime();
            final String[] inputDeep = {""};
        List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.selectChildBySpokes(aiRecordingDuan);
            if (!aiRecordingChildList.isEmpty()){
                aiRecordingChildList.forEach(child->{
                    if ( child.getSpearName()!=null && !child.getSpearName().isEmpty() &&   child.getSpearName().equals("销售")){
                        inputDeep[0] = inputDeep[0] +"\n"+"sales manager:"+child.getTranscript();
                    }else  if ( child.getSpearName()==null   ||  child.getSpearName().isEmpty() ||   child.getSpearName().equals("其他")){
                        inputDeep[0] = inputDeep[0] +"\n"+"unclear:"+child.getTranscript();
                    }
                    else {
                        inputDeep[0] = inputDeep[0] +"\n"+"customer:"+child.getTranscript();
                    }
                });
                inputDeep[0] =getFenxiDict()+ inputDeep[0];
                getDeepSeek(mainId,inputDeep[0],duanId,batchId);
            }

        getDeepSeekForTotal(customerId);

    }

    /**
     * 生成总的总结
     * @param customerId
     * @throws Exception
     */
    public  void getDeepSeekForTotal( Long customerId) throws Exception {
        final String[] inputDeepTotal = {""};
        List<AiRecordingChild>  aiRecordingChildListTotal=  aiRecordingChildMapper.selectChildBySpokesTotal(customerId);
        if (!aiRecordingChildListTotal.isEmpty()){
                aiRecordingChildListTotal.forEach(child->{
                    if ( child.getSpearName()!=null && !child.getSpearName().isEmpty() &&   child.getSpearName().equals("销售")){
                        inputDeepTotal[0] = inputDeepTotal[0] +"\n"+"sales manager:"+child.getTranscript();
                    }else  if ( child.getSpearName()==null   ||  child.getSpearName().isEmpty() ||   child.getSpearName().equals("其他")){
                        inputDeepTotal[0] = inputDeepTotal[0] +"\n"+"unclear:"+child.getTranscript();
                    }
                    else {
                        inputDeepTotal[0] = inputDeepTotal[0] +"\n"+"customer:"+child.getTranscript();
                    }
                });
                inputDeepTotal[0] =getFenxiDict()+ inputDeepTotal[0];
                getDeepSeekTotal(customerId,inputDeepTotal[0]);
        }
    }

    @Async // 标记为异步方法
    public  String getDeepSeekTotal(Long customerId, String json) throws InterruptedException {
        while (true) {
            try {
                String effective="";
                String response = deepSeekClient.chatCompletion(json,true);
                System.out.println("deepseek结果---"+response);
                String cleanedString = RemoveQuotesAndBrackets.removeQuotesAndBrackets(response.replaceAll("json", "").replaceAll("txt", "").replace("`",""));
                // 根据逗号分隔字符串
                List<String> parts = RemoveQuotesAndBrackets.splitByComma(cleanedString);
                aiDeepseekAnswerTotalMapper.deleteAiDeepseekAnswerTotalByCustomerId(customerId);
                // 打印结果
                for (String part : parts) {
                    AiDeepseekAnswerTotal aiDeepseekAnswerTotal=new AiDeepseekAnswerTotal();
                    String[] typeName=  part.split(":");
                    if (typeName.length>0){
                        aiDeepseekAnswerTotal.setTypeName(typeName[0].replaceAll("\\s", ""));
                        if (typeName.length>=2){
                            aiDeepseekAnswerTotal.setContent(typeName[1].replaceAll("\\s", ""));
                            if (aiDeepseekAnswerTotal.getTypeName().contains("有效交流") && aiDeepseekAnswerTotal.getContent().contains("有效")){
                                effective="1";
                            }
                            if ( (aiDeepseekAnswerTotal.getTypeName().contains("流失风险")|| aiDeepseekAnswerTotal.getTypeName().contains("成交意愿")) && !aiDeepseekAnswerTotal.getTypeName().contains("说明") ){
                                if (aiDeepseekAnswerTotal.getContent().contains("高")){
                                    aiDeepseekAnswerTotal.setContent("高");
                                }else if (aiDeepseekAnswerTotal.getContent().contains("低")){
                                    aiDeepseekAnswerTotal.setContent("低");
                                }
                            }
                        }
                    }
                    aiDeepseekAnswerTotal.setCustomerId(customerId);
                    aiDeepseekAnswerTotal.setCreateTime(new Date());
                    if (aiDeepseekAnswerTotal.getTypeName()!=null && !aiDeepseekAnswerTotal.getTypeName().equals("")){
                        aiDeepseekAnswerTotalMapper.insertAiDeepseekAnswerTotal(aiDeepseekAnswerTotal);
                    }
                }

              CustomerInfo customerInfo=   customerInfoMapper.selectCustomerInfoById(customerId);
//                if (customerInfo.getFirstTime()==null){
//                    customerInfo.setFirstTime(time);
//                }
//                if (customerInfo.getDurationCommunication()==null){
//                    customerInfo.setDurationCommunication(validTime);
//                }else{
//                    customerInfo.setDurationCommunication(customerInfo.getDurationCommunication()+validTime);
//                }
//                if (effective.equals("1")){
                    customerInfo.setEffective(effective);
//                }
                customerInfoMapper.updateCustomerInfo(customerInfo);
                return response;
            } catch (IOException e) {
                System.out.println("错误...，"+e.getMessage().toString() );
                System.out.println("deepseek进行中(总的)...，" );
                //建议使用回调的方式查询结果，查询接口有请求频率限制
                Thread.sleep(7000);
            }
        }
    }
    @Async // 标记为异步方法
    public  String getDeepSeek(Long mainId, String json,Long duanId,String   batchId) throws InterruptedException {
        while (true) {
            try {
                String response = deepSeekClient.chatCompletion(json,true);
                System.out.println("deepseek结果---"+response);
                String cleanedString = RemoveQuotesAndBrackets.removeQuotesAndBrackets(response.replaceAll("json", "").replaceAll("txt", "").replace("`",""));
                // 根据逗号分隔字符串
                List<String> parts = RemoveQuotesAndBrackets.splitByComma(cleanedString);
                // 打印结果
                for (String part : parts) {
                    AiDeepseekAnswer aiDeepseekAnswer=new AiDeepseekAnswer();
                    aiDeepseekAnswer.setDuanId(duanId);
                   String[] typeName=  part.split(":");
                   if (typeName.length>0){
                       aiDeepseekAnswer.setTypeName(typeName[0].replaceAll("\\s", ""));
                       if (typeName.length>=2){
                           aiDeepseekAnswer.setContent(typeName[1].replaceAll("\\s", ""));
                           if ( (aiDeepseekAnswer.getTypeName().contains("流失风险")|| aiDeepseekAnswer.getTypeName().contains("成交意愿")) && !aiDeepseekAnswer.getTypeName().contains("说明") ){
                               if (aiDeepseekAnswer.getContent().contains("高")){
                                   aiDeepseekAnswer.setContent("高");
                               }else if (aiDeepseekAnswer.getContent().contains("低")){
                                   aiDeepseekAnswer.setContent("低");
                               }
                           }
                       }
                   }
                    aiDeepseekAnswer.setCreateTime(new Date());
                    aiDeepseekAnswer.setMainId(mainId);
                    aiDeepseekAnswer.setBatchId(batchId);
                    if (aiDeepseekAnswer.getTypeName()!=null && !aiDeepseekAnswer.getTypeName().equals("")){
                        aiDeepseekAnswerMapper.insertAiDeepseekAnswer(aiDeepseekAnswer);
                    }
                }
                AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
                aiRecordingDuan.setId(duanId);
                aiRecordingDuan.setStatus("2");
                aiRecordingDuanMapper.updateAiRecordingDuan(aiRecordingDuan);
                aiRecordingDuan.setStatus("1");
                aiRecordingDuan.setId(null);
                aiRecordingDuan.setMainId(mainId);
                 List<AiRecordingDuan>  aiRecordingDuanList=    aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan);
                AiRecordingMain aiRecordingMain=new AiRecordingMain();
                aiRecordingMain.setId(mainId);
                 if (!aiRecordingDuanList.isEmpty()){
                     aiRecordingMain.setStatus("5");
                 }else{
                     aiRecordingMain.setStatus("6");
                 }
                aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
                return response;
            } catch (IOException e) {
                System.out.println("错误...，"+e.getMessage().toString() );
                System.out.println("deepseek进行中...，" );
                //建议使用回调的方式查询结果，查询接口有请求频率限制
                Thread.sleep(7000);
            }
        }
    }
    public void getXunFeiResult(AiRecordingMain aiRecordingMain) throws Exception {
        AiRecordingMain aiRecordingMain1=new AiRecordingMain();
        aiRecordingMain1.setOrderId(aiRecordingMain.getOrderId());
        AiRecordingMain  aiRecordingMainOld=    aiRecordingMainMapper.selectAiRecordingMainList(aiRecordingMain1).get(0);
//        String orderId,Long mainId,Long fileId, String  segmented
        String orderId=aiRecordingMainOld.getOrderId();
        Long mainId=aiRecordingMainOld.getId();
        Long fileId=aiRecordingMainOld.getFileId();
        String  segmented=aiRecordingMainOld.getSegmented();
        iXunFeiService.getResultUtil(orderId,mainId,fileId,segmented,null,null);
    }

    @Override
    public List<AiRecordingDuan> selectCustomerTime(){
        AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
        aiRecordingDuan.setUserId(SecurityUtils.getUserId());
        List<AiRecordingDuan>  aiRecordingDuanList=    aiRecordingDuanMapper.selectCustomerTime(aiRecordingDuan);
        return aiRecordingDuanList;
    }


    @Override
    public List<AiRecordingDuan> selectGroupTime(AiRecordingDuan aiRecordingDuan){
        List<AiRecordingDuan>  aiRecordingDuanList=    aiRecordingDuanMapper.selectGroupTime(aiRecordingDuan);
        return aiRecordingDuanList;
    }

    @Override
    public List<AiRecordingDuan> selectGroupPerson(){
        List<AiRecordingDuan>  aiRecordingDuanList=    aiRecordingDuanMapper.selectGroupPerson();
        return aiRecordingDuanList;
    }
//

    /**
     * 查询录音文件上传记录
     *
     * @param id 录音文件上传记录主键
     * @return 录音文件上传记录
     */
    @Override
    public AiRecordingMain selectAiRecordingMainById(Long id)
    {
        return aiRecordingMainMapper.selectAiRecordingMainById(id);
    }

    /**
     * 查询录音文件上传记录列表
     *
     * @param aiRecordingMain 录音文件上传记录
     * @return 录音文件上传记录
     */
    @Override
    public List<AiRecordingMain> selectAiRecordingMainList(AiRecordingMain aiRecordingMain)
    {
        Long userId= SecurityUtils.getUserId();
        SysUserRole sysUserRole =new SysUserRole();
        sysUserRole.setRoleId(100L);
        sysUserRole.setUserId(userId);
        Integer coun= sysUserRoleMapper.countUserRoleByRoleIdUserId(sysUserRole);
        if (coun == 0 && userId!=1L){
            aiRecordingMain.setUserId(userId);
        }
        PageUtils.startPage();
        List<AiRecordingMain> aiRecordingMainList=aiRecordingMainMapper.selectAiRecordingMainList(aiRecordingMain);

//
//        AiRecordingMain aiRecordingMain1=new AiRecordingMain();
//
//        List<AiRecordingMain> aiRecordingMainList1=aiRecordingMainMapper.selectAiRecordingMainList(aiRecordingMain1);
//
//        aiRecordingMainList1.forEach(main->{
//
//
//            aiDeepseekSpokesmanMapper.selectSpareString(main);
//
//
//        });
//

        return aiRecordingMainList;
    }

    /**
     * 新增录音文件上传记录
     *
     * @param aiRecordingMain 录音文件上传记录
     * @return 结果
     */
    @Override
    public int insertAiRecordingMain(AiRecordingMain aiRecordingMain)
    {
        aiRecordingMain.setCreateTime(DateUtils.getNowDate());
        return aiRecordingMainMapper.insertAiRecordingMain(aiRecordingMain);
    }
    @Override
    public int insertAiRecordingMainFile(String path,String avatar,String language, String  segmented,Long costomerId, Date time) throws Exception {

        Long userId= SecurityUtils.getUserId();
        Long deptId= null;
        String userName= null;
        if (userId==null){
//            todo 未确定
//            SysUser sysUser= sysUserMapper.selectUserById(userId);
//            deptId=sysUser.getDeptId();
//            userName=sysUser.getUserName();
        }else{
            deptId=SecurityUtils.getDeptId();
            userName=SecurityUtils.getUsername();
        }
        path= RuoYiConfig.getProfile()+path;
        SystemFile systemFile = new SystemFile();
        systemFile.setPath(path);
        systemFile.setCreateTime(new Date());
        systemFile.setAddress(avatar);
        systemFile.setCreateBy(userId+"");
        // 找到最后一个斜杠的位置
        int lastSlashIndex = path.lastIndexOf("/");
        // 截取最后一个斜杠后面的部分
        String fileName = path.substring(lastSlashIndex + 1);
        systemFile.setName(fileName);
        systemFileMapper.insertSystemFile(systemFile);

        AiRecordingMain aiRecordingMain=new AiRecordingMain();
        aiRecordingMain.setLanguages(language);
        aiRecordingMain.setFileId(systemFile.getId());
        aiRecordingMain.setCreateTime(DateUtils.getNowDate());
        aiRecordingMain.setCreateBy(userName);
        aiRecordingMain.setUserId(userId);
        aiRecordingMain.setDeptId(deptId);
        aiRecordingMain.setSegmented(segmented);
//        aiRecordingMain.setcreate
        aiRecordingMain.setStatus("1");
         aiRecordingMainMapper.insertAiRecordingMain(aiRecordingMain);


        // 创建一个新线程执行异步任务
        String finalPath = path;
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                String orderId= iXunFeiService.xunfeiUtil(finalPath,aiRecordingMain.getId(),systemFile.getId(),language,segmented,costomerId,time);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });

        // 启动线程
        thread.start();

        return 1;
    }

    public AjaxResult deleteRemoveDuan(AiRecordingDuan aiRecordingDuan){
        AiRecordingDuan aiRecordingDuan1=new AiRecordingDuan();
        aiRecordingDuan1.setMainId(aiRecordingDuan.getMainId());
        List<AiRecordingDuan> aiRecordingDuanList= aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan1);
        if (aiRecordingDuanList.size()==1){
            deleteRemoveMain(aiRecordingDuan);
        }else{
            deleteRemoveDuanOne(aiRecordingDuan);
        }
        return AjaxResult.success();
    }

    public AjaxResult deleteRemoveDuanOne(AiRecordingDuan aiRecordingDuan){
        Long duanId=aiRecordingDuan.getId();
//        AiRecordingDuan aiRecordingDuanOld=  aiRecordingDuanMapper.selectAiRecordingDuanById(duanId);
        Long customerIdOld=  aiRecordingDuan.getCustomerId();
        aiDeepseekAnswerTotalMapper.deleteAiDeepseekAnswerTotalByCustomerId(customerIdOld);
        aiRecordingDuanMapper.deleteAiRecordingDuanById(duanId);
        aiDeepseekSpokesmanMapper.deleteAiDeepseekSpokesmanById(duanId);
        aiDeepseekAnswerMapper.deleteByDuanId(duanId);

        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                getDeepSeekForTotal(customerIdOld);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });
        // 启动线程
        thread.start();
        return AjaxResult.success();
    }

    public AjaxResult deleteRemoveMain(AiRecordingDuan aiRecordingDuan){
        if (SecurityUtils.getUserId()!=1L) {
            return AjaxResult.error("当前登录人无权限操作");
        }
        Long mainId=aiRecordingDuan.getMainId();
        AiRecordingMain aiRecordingMainStatus=   aiRecordingMainMapper.selectAiRecordingMainById(mainId);
        if (!aiRecordingMainStatus.getStatus().equals("3") && !aiRecordingMainStatus.getStatus().equals("6")){
            return AjaxResult.error("该数据当前状态无法进行该操作");
        }
        AiRecordingDuan aiRecordingDuan1=new AiRecordingDuan();
        aiRecordingDuan1.setMainId(mainId);
        List<AiRecordingDuan> aiRecordingDuanList= aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan1);
        if (aiRecordingDuanList.size()!=0){
            Thread thread1 = new Thread(() -> {
                // 模拟耗时操作
                try {
                    aiRecordingDuanList.forEach(duan->{
                        AiRecordingDuan aiRecordingDuan2=new AiRecordingDuan();
                        aiRecordingDuan2.setId(duan.getId());
                        aiRecordingDuan2.setMainId(duan.getMainId());
                        aiRecordingDuan2.setCustomerId(duan.getCustomerId());
                        deleteRemoveDuanOne(aiRecordingDuan2);
                    });
                }  catch (Exception e) {
                    throw new RuntimeException(e);
                }
                System.out.println("异步任务完成");
            });
            // 启动线程
            thread1.start();
            aiRecordingDuanMapper.deleteByMainId(mainId);
            aiDeepseekAnswerMapper.deleteByMainId(mainId);
            aiDeepseekSpokesmanMapper.deleteByMainId(mainId);
        }
        aiRecordingChildMapper.deleteByMainId(mainId);
        return AjaxResult.success();
    }
    public AjaxResult updateMainDateCustomerName(AiRecordingDuan aiRecordingDuan) throws InterruptedException {
        Long duanId=aiRecordingDuan.getId();
        AiRecordingDuan aiRecordingDuanOld=  aiRecordingDuanMapper.selectAiRecordingDuanById(duanId);
        Long customerIdOld=  aiRecordingDuanOld.getCustomerId();
        Long customerIdNew=   aiRecordingDuan.getCustomerId();
        aiDeepseekAnswerTotalMapper.deleteAiDeepseekAnswerTotalByCustomerId(customerIdOld);
        aiDeepseekAnswerTotalMapper.deleteAiDeepseekAnswerTotalByCustomerId(customerIdNew);
        aiRecordingDuanMapper.updateAiRecordingDuan(aiRecordingDuan);
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                getDeepSeekForTotal(customerIdOld);
                getDeepSeekForTotal(customerIdNew);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });
        // 启动线程
        thread.start();
        return AjaxResult.success();
    }


    public AjaxResult updateMainDate(AiRecordingMain aiRecordingMain){
        if (SecurityUtils.getUserId()!=1L) {
            return AjaxResult.error("当前登录人无权限操作");
        }
        Long mainId=aiRecordingMain.getId();

        AiRecordingMain aiRecordingMainStatus=   aiRecordingMainMapper.selectAiRecordingMainById(mainId);
        if (!aiRecordingMainStatus.getStatus().equals("3") && !aiRecordingMainStatus.getStatus().equals("6")){
            return AjaxResult.error("该数据当前状态无法进行该操作");
        }

        aiRecordingMain.setStatus("1");
        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);

        AiRecordingMain aiRecordingMain1=   aiRecordingMainMapper.selectAiRecordingMainById(aiRecordingMain.getId());
        AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
        aiRecordingDuan.setMainId(mainId);
        List<AiRecordingDuan> aiRecordingDuanList= aiRecordingDuanMapper.selectAiRecordingDuanList(aiRecordingDuan);
        if (!aiRecordingDuanList.isEmpty()){
            Thread thread1 = new Thread(() -> {
                // 模拟耗时操作
                try {
                    aiRecordingDuanList.forEach(duan->{
//                    aiRecordingDuanMapper.deleteByMainId(duan.getId());
                        AiRecordingDuan aiRecordingDuan1=new AiRecordingDuan();
                        aiRecordingDuan1.setId(duan.getId());
                        aiRecordingDuan1.setMainId(duan.getMainId());
                        aiRecordingDuan1.setCustomerId(duan.getCustomerId());
                        try {
                            updateMainDateCustomerNameTwo(aiRecordingDuan1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }  catch (Exception e) {
                    throw new RuntimeException(e);
                }
                System.out.println("异步任务完成");
            });
            // 启动线程
            thread1.start();
            aiRecordingDuanMapper.deleteByMainId(mainId);
            aiDeepseekAnswerMapper.deleteByMainId(mainId);
            aiDeepseekSpokesmanMapper.deleteByMainId(mainId);
        }
        aiRecordingChildMapper.deleteByMainId(mainId);
       SystemFile systemFile= systemFileMapper.selectSystemFileById(aiRecordingMain1.getFileId());
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                String orderId= iXunFeiService.xunfeiUtil(systemFile.getPath(),aiRecordingMain.getId(),systemFile.getId(),aiRecordingMain.getLanguages(),aiRecordingMain.getSegmented(),null,null);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });
        // 启动线程
        thread.start();

        return AjaxResult.success();
    }

    public AjaxResult updateMainDateCustomerNameTwo(AiRecordingDuan aiRecordingDuan) throws InterruptedException {
        Long customerId=  aiRecordingDuan.getCustomerId();
        aiDeepseekAnswerTotalMapper.deleteAiDeepseekAnswerTotalByCustomerId(customerId);
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                getDeepSeekForTotal(customerId);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });
        // 启动线程
        thread.start();
        return AjaxResult.success();
    }

    @Override
    public AjaxResult segmentedByDeepSeek(AiRecordingMain aiRecordingMain){
         Long mainId=aiRecordingMain.getId();
        AiRecordingMain aiRecordingMain1=  aiRecordingMainMapper.selectAiRecordingMainById(mainId);
        if (aiRecordingMain1.getSegmented().equals("true")){
            return AjaxResult.error("该录音已分段，请刷新界面");
        }
        aiRecordingMain.setStatus("2");
        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            try {
                iXunFeiService.getDeepSeek(aiRecordingMain.getId(),"true",null,null,null);
            }  catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("异步任务完成");
        });
        // 启动线程
        thread.start();
       return AjaxResult.success();
    }

    /**
     * 修改录音文件上传记录
     *
     * @param aiRecordingMain 录音文件上传记录
     * @return 结果
     */
    @Override
    public int updateAiRecordingMain(AiRecordingMain aiRecordingMain)
    {
        aiRecordingMain.setUpdateTime(DateUtils.getNowDate());
        return aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
    }

    /**
     * 批量删除录音文件上传记录
     *
     * @param ids 需要删除的录音文件上传记录主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingMainByIds(Long[] ids)
    {
        return aiRecordingMainMapper.deleteAiRecordingMainByIds(ids);
    }

    /**
     * 删除录音文件上传记录信息
     *
     * @param id 录音文件上传记录主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingMainById(Long id)
    {
        return aiRecordingMainMapper.deleteAiRecordingMainById(id);
    }
}
